package com.xs.designpattern;

import lombok.extern.slf4j.Slf4j;

import java.util.EnumMap;
import java.util.Map;

/**
 * 生成药水的工厂
 * @author xs
 */
@Slf4j
public class PotionFactory {
    /**
     * 存放要药水的map货架
     */
    private final Map<PotionType, Potion> potions;

    /**
     * 狗构造函数指定map的枚举map类型
     */
    public PotionFactory() {
        potions = new EnumMap<>(PotionType.class);
    }

    /**
     * 通过类型创建药水，以及创建的药水类型直接拿来使用，减少资源的浪费，避免频繁的创建对象
     * @param type 药水的类型
     * @return 返回药水的实例
     */
    Potion createPotion(PotionType type) {
        Potion potion = potions.get(type);
        //如果药水类型对应的对象没有创建就走进if内部，创建了的话直接返回这个对象的实例就行
        if (potion == null) {
            switch (type) {
                case HEALING:
                    potion = new HealingPotion();
                    break;
                case HOLY_WATER:
                    potion = new HolyWaterPotion();
                    break;
                case INVISIBILITY:
                    potion = new InvisibilityPotion();
                    break;
                case POISON:
                    potion = new PoisonPotion();
                    break;
                case STRENGTH:
                    potion = new StrengthPotion();
                    break;
                default:
                    log.info("没有这种的药水类型！");
            }
            //如何药水在map中是空的我们就把上面创建的对象放到map中进行二次使用
            if (potion != null) {
                potions.put(type, potion);
            }
        }
        //返回实例的对象
        return potion;
    }
}
